// 面试题32 - I. 从上到下打印二叉树

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function levelOrder(root: TreeNode | null): number[] {
  if (!root) return [];
  const stack: [TreeNode | null, number][] = [[root, 0]];
  const result: number[][] = [];

  while (stack.length) {
    const [node, level] = stack.shift();
    if (!result[level]) {
      result[level] = [node.val];
    } else {
      result[level].push(node.val);
    }

    node.left && stack.push([node.left, level + 1]);
    node.right && stack.push([node.right, level + 1]);
  }

  return result.flat();
}
